package com.bw.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.entity.User;
import com.bw.mapper.UserMapper;
import org.spring.kun.common.GiteeUtils;
import org.spring.kun.common.Md5Utils;
import org.spring.kun.common.TokenUtils;
import org.spring.kun.common.ZzyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class GiteeLoginController {

    @Autowired
    UserMapper userMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping("/callbackCode.do")
    public String callback(String code, HttpServletResponse response) {
        System.out.println("接收到的临时授权码" + code);
        String accessTokenByCode = GiteeUtils.getAccessTokenByCode(code);
        System.out.println("获取到的token" + accessTokenByCode);

        JSONObject userInfoByToken = GiteeUtils.getGiteeUserInfoByToken(accessTokenByCode);

        System.out.println("获取到的用户信息" + JSON.toJSONString(userInfoByToken));

        Integer giteeId = userInfoByToken.getInteger("id");
        String name = userInfoByToken.getString("login");
        String nickName = userInfoByToken.getString("name");
        String avatarUrl = userInfoByToken.getString("avatar_url");

        User userFromDB = userMapper.selectByName(name);
        if (userFromDB == null) {
            User newUser = new User();
            newUser.setName(name);
            newUser.setNickName(nickName);
            newUser.setAvatarUrl(avatarUrl);
            newUser.setGiteeId(giteeId);

            // 设置默认密码
            String str = "123";
            String salt = UUID.randomUUID().toString().substring(0, 8);
            newUser.setSalt(salt);

            String md5String = Md5Utils.getMD5String(str + salt);
            newUser.setPassword(md5String);

            // 执行注册
            userMapper.add(newUser);
            // 加密用户 生成令牌

            TokenUtils.responseTokenByCookie(newUser, response);
            //使用Redis保存登录的用户信息，设置过期时间为cookie的过期时间
            redisTemplate.opsForValue().set("user", JSON.toJSONString(newUser), 30, TimeUnit.MINUTES);

            //用户在什么时间登录系统
            boolean b = ZzyUtils.sendSms("17611221735", name + "在" + System.currentTimeMillis() + "登录了系统", 5);
            //要求有短信发送成功回调的信息输出
            if (b){
                System.out.println("短信发送成功");
            }
        } else {
            //如果以前注册过 刷新一下 头像和昵称

            userFromDB.setAvatarUrl(avatarUrl);
            userFromDB.setNickName(nickName);
            userMapper.updateUser(userFromDB);
            // 重新加密用户 生成令牌
            TokenUtils.responseTokenByCookie(userFromDB, response);
            //使用Redis保存登录的用户信息，设置过期时间为cookie的过期时间
            redisTemplate.opsForValue().set("user", JSON.toJSONString(userFromDB), 30, TimeUnit.MINUTES);

            //用户在什么时间登录系统
            boolean b = ZzyUtils.sendSms("17611221735", name + "在" + System.currentTimeMillis() + "登录了系统", 5);
            //要求有短信发送成功回调的信息输出
            if (b){
                System.out.println("短信发送成功");
            }
        }

        return "redirect:list.do";

    }

    @RequestMapping("/list.do")
    public String list(Model model, HttpServletRequest request){

        // 从request中解析出用户

        User userFromRequest = TokenUtils.getLoginUserFromRequest(request, User.class);

        model.addAttribute("nickName",userFromRequest.getNickName());
        model.addAttribute("avatarUrl",userFromRequest.getAvatarUrl());
        return "list";
    }

}
